package com.fingard.dsp.bank.directbank.jhbank02.utils;

import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;


public class Decipher {
	/**
	 * ˽Կ����
	 * 
	 * @param merchant_id @param data @param encryptkey @return @throws
	 */

	private static String certificatePath= "E:\\certificate\\88887_qy.cer";
	private static String keyStorePath= "E:\\certificate\\88887_qy.pfx";
	
	
	public static String decryptData(Map<String, String> map, String pfx) throws Exception {

		String encryptkey = map.get("encryptkey");
		String encryptdata = map.get("encryptdata");

		// ��ȡ�Լ�˽Կ����
		//System.out.println("keyStorePath"+"="+keyStorePath);
		
		PrivateKey pvkformPfx = RSA.getPvkformPfx(pfx, "123456");
		String decryptData = RSA.decrypt(encryptkey, pvkformPfx);

		String post = AES.decryptFromBase64(encryptdata, decryptData);

		return post;
	}

	/**
	 * ��Կ����
	 * 
	 * @param @param data @param encryptkey @return @throws
	 */
	public static Map<String, String> encryptData(String json, String cer) throws Exception {
//		System.out.println("json����=============>" + json);

		// ��ȡ��Կ
		PublicKey pubKeyFromCrt = RSA.getPubKeyFromCRT(cer);
		// �������16����
		String key = getRandom(16);
		// ʹ��RSA�㷨���Լ�������ɵ�AESkey����
		String encryptKey = RSA.encrypt(key, pubKeyFromCrt);
		// ʹ��AES�㷨��������ɵ�AESkey����json�����м���
		String encryData = AES.encryptToBase64(json, key);

//		System.out.println("����key============>" + encryptKey);
//		System.out.println("��������===========>" + encryData);

		Map<String, String> map = new HashMap<String, String>();
		map.put("encryptdata", encryData);
		map.put("encryptkey", encryptKey);

		return map;
	}
	
	/*
	 * ˽Կǩ��
	 */
	public static String sign(String str, String pfx) throws Exception{
		PrivateKey pvkformPfx = RSA.getPvkformPfx(pfx, "123456");
		String str1=RSA.sign(str, pvkformPfx);
		return   str1;		
	}
	
	
	public static boolean checkSign(String str,String sign, String cer) throws Exception{
		PublicKey pubKeyFromCrt = RSA.getPubKeyFromCRT(cer);
		boolean  b=RSA.checkSign(str, sign, pubKeyFromCrt);
		return b;
		
	}
	
	public static Random random = new Random();

	public static String getRandom(int length) {
		StringBuilder ret = new StringBuilder();
		for (int i = 0; i < length; i++) {
			boolean isChar = (random.nextInt(2) % 2 == 0);// �����ĸ��������
			if (isChar) { // �ַ���
				int choice = (random.nextInt(2) % 2 == 0) ? 65 : 97; // ȡ�ô�д��ĸ����Сд��ĸ
				ret.append((char) (choice + random.nextInt(26)));
			} else { // ����
				ret.append(Integer.toString(random.nextInt(10)));
			}
		}
		return ret.toString();
	}

	public static void main(String[] args) {

	}

}
